<?php

require_once(WSB_MODULES_PATH . 'cms/Url.php');

class Cms_ContainerController extends Zend_Controller_Action
{

    public function indexAction()
    {
        $this->_helper->Redirect(Cms_Url::containerEditUrl());
    }

    public function deleteContainerAction()
	{
        $text = sprintf($this->_helper->Translate('deleteContainer.confirmation'), $this->_getParam('idcontainer'));
        // Als POPUP aus dem Frontend aufgerufen
        if($this->_getParam('TEMPLATE') == 'popup') {
            $this->view->text = $text;
    		if($this->_getParam('YES') != '') {
    			$table = new Cms_Model_DbTable_Container();
                $table->deleteContainer($this->_getParam('idcontainer'));
                WSB_Log::info(sprintf('Deleted container %s', $this->_getParam('idcontainer')));
                $this->_response->appendBody('
                <script type="text/javascript">
                    window.opener.location.reload();
                    window.close();
                </script>
                ');
    		}
        } else {
        	/*
    		$answer = WSB_Dialog::ConfirmDialog($text);
    		if($answer == WSB_Dialog::YES_OPTION) {
    			$table = new Cms_Model_DbTable_Container();
    			$table->deleteContainer($this->_getParam('idcontainer'));
    			WSB_Log::info(sprintf('Deleted container %s', $this->_getParam('idcontainer')));
    			$this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
    		}
    		if($answer == WSB_Dialog::NO_OPTION) {
        		$this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
    		}
    		$this->_forward('edit', null, null, array('page_id' => $this->_getParam('page_id')));
    		*/
			$table = new Cms_Model_DbTable_Container();
			$table->deleteContainer($this->_getParam('idcontainer'));
			WSB_Log::info(sprintf('Deleted container %s', $this->_getParam('idcontainer')));
			$this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
        }
    }

    public function moveUpAction()
	{
		$table = new Cms_Model_DbTable_Container();
		$table->moveContainer($this->_getParam('idcontainer'), 'up');
		WSB_Log::info(sprintf('Moved container %s up', $this->_getParam('idcontainer')));
		if($this->_getParam('REDIRECT') != '') {
		  $this->_helper->Redirect($this->_getParam('REDIRECT'));
		} else {
		  $this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
		}
    }

    public function moveDownAction()
	{
		$table = new Cms_Model_DbTable_Container();
		$table->moveContainer($this->_getParam('idcontainer'), 'down');
		WSB_Log::info(sprintf('Moved container %s down', $this->_getParam('idcontainer')));
		if($this->_getParam('REDIRECT') != '') {
		  $this->_helper->Redirect($this->_getParam('REDIRECT'));
		} else {
		  $this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
		}
    }

    public function configurationAction()
	{

    	$table = new Cms_Model_DbTable_Container();
		$where = $table->getAdapter()->quoteInto('id=?', $this->_getParam('id'));
		$row = $table->fetchRow($where);

    	// Formulardaten speichern
    	if($this->getRequest()->isPost()) {
    		$POST = $this->getRequest()->getPost($table->getClass());
    		if(is_array($POST) && (count($POST) > 0)) {
    			$hasChanged = false;
    			foreach($POST AS $key=>$value) {
    				if($row->$key != $value) {
    					$hasChanged = true;
    				}
					$row->$key = $value;
    			}
    			if($hasChanged) {
    				$row->save();
    			}
    		}
    	}

		$this->view->row = $row;
		$this->view->action = $_SERVER['REQUEST_URI'];
		$this->view->onclick = sprintf("javascript:window.location.href='%s'", Cms_Url::containerEditUrl($row->page_id));

    	$this->render();

    	// Page Tree rendern
    	$this->render('container-tree', 'left', true);
    }

    public function editAction()
	{

    	$session = $this->getHelper('Session');

    	// Die letzte Ansicht merken ($pageId aus Request oder Session holen)
    	$pageId = intval($this->_getParam('page_id'));
		if(empty($pageId)) {
			$pageId = $session->page_id;
		} else {
	    	$session->page_id = $pageId;
		}

    	$tree = WSB_Node_Page::getTree();
    	$page = $tree->getPage($pageId);
		if(!$page instanceof Cms_Model_Page) {
			$page = $tree->getPage($tree->getId());
			$session->page_id = $page->id;
		}
		if(!$page instanceof Cms_Model_Page) {
			$this->render('no-page');
			$session->page_id = null;
			return;
		}

		$languages = $page->getLanguages();
		if(count($languages) == 0) {
			$this->render('no-languages');
			return;
		}

	    $template = $page->getTemplate();
		if(!$template instanceof Cms_Model_Template) {
			$this->render('no-template');
			return;
		}

		$this->view->page = $page;
		$this->view->template = $template;
		$this->view->languages = $languages;
	    $this->view->parentPageContainerSet = $page->getParentPageContainers(false);
	    $this->view->pageContainerSet = $page->getContainers(true);

	    $this->render();

    	// Page Tree rendern
    	$this->view->pageId = $pageId;
    	$this->render('container-tree', 'left', true);
    }

    public function hideAction()
	{
        $table = new Cms_Model_DbTable_Container();
        $where = $table->getAdapter()->quoteInto('id=?', $this->_getParam('container_id'));
        $row = $table->fetchRow($where);
    	$row->hidden = 1;
    	$row->save();
    	if($this->_getParam('REDIRECT') != '') {
		  $this->_helper->Redirect($this->_getParam('REDIRECT'));
		} else {
    		$this->_forward('edit');
		}
    }

    public function unhideAction()
	{
        $table = new Cms_Model_DbTable_Container();
        $where = $table->getAdapter()->quoteInto('id=?', $this->_getParam('container_id'));
        $row = $table->fetchRow($where);
    	$row->hidden = 0;
    	$row->save();
		if($this->_getParam('REDIRECT') != '') {
		  $this->_helper->Redirect($this->_getParam('REDIRECT'));
		} else {
    		$this->_forward('edit');
		}
    }

    public function addContainerAction()
	{

    	$this->_helper->viewRenderer->setNoRender();

        // 1. Schritt: Parameter holen
		$params = $this->_getAllParams();
		unset($params['module']);
		unset($params['controller']);
		unset($params['action']);

		// FE-Controller
		$params['controller'] = $params['fectrl'];
		$frontendCtrlClassname = $params['fectrl'];
		unset($params['fectrl']);

        // 2. Schritt: Falls es sich um eine Contentelement handelt,
        // einen neuen Eintrag in der entsprechenden Tabelle machen.
        $instance_id = $this->_getParam('instance_id');
        $params['item_id'] = 0;
        if(!empty($instance_id) && is_numeric($instance_id)) {
        	$table = new Cms_Model_DbTable_Xtension();
        	$where = $table->getAdapter()->quoteInto('id=?', $instance_id);
            $instance = $table->fetchRow($where);

			$filename = str_replace(ucfirst($instance->class).'_', '', $frontendCtrlClassname).'.php';
			$dir = WSB_XTENSION_PATH . sprintf('%s/controllers/', strtolower($instance->class));
			Zend_Loader::loadFile($filename, $dir, true);

            $XT = new $frontendCtrlClassname();
			$XT->setModule($instance);
            if($XT instanceof WSB_Xtension_Content) {
                $extTable = $XT->getTable();
                $extItem = $extTable->createRow();
                $extItem->save();
                $params['item_id'] = $extItem->getPrimaryValue();
            }
        }

        // 3. Schritt: Container speichern
        $table = new Cms_Model_DbTable_Container();
    	$containerId = $table->addContainer($params);
		WSB_Log::info(sprintf('Added container with id %s', $containerId));

		/*
		if($XT instanceof WSB_Xtension_Extension) {
			// xtnews/index/list/instance_id/13/
			$this->_helper->Redirect(Cms_Url::xtensionEditorUrl($containerId, $XT));
		}
		*/

		if ($XT instanceof WSB_Xtension_Content) {
			// Container holen und setzen
			$where = $table->getAdapter()->quoteInto('id=?', $containerId);
			$container = $table->fetchRow($where);
			$XT->setContainer($container);

			// xthtml/index/edit/id/2/
			$referer = Cms_Url::containerEditUrl($params['page_id']);
			$this->_helper->Redirect(Cms_Url::xtensionEditorUrl($containerId, $XT, $referer));
		}

        if($this->_getParam('TEMPLATE') == 'popup') {
            $this->_response->appendBody('
            <script type="text/javascript">
                window.opener.location.reload();
                window.close();
            </script>
            ');
        } else {
		  $this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
        }
    }

    public function addflexAction()
	{

    	$this->_helper->viewRenderer->setNoRender();

        $pageId = intval($this->_getParam('page_id'));
        $placeholderId = intval($this->_getParam('placeholder_id'));
        $sort = intval($this->_getParam('sort'));
        $languageId = intval($this->_getParam('language_id'));
        $flexId = intval($this->_getParam('flex_id'));


        // FlexId pruefen
        if($flexId <= 0) {
            $url = Cms_Url::containerSelectModuleUrl(
                $pageId,
                $placeholderId,
                $sort,
                $languageId
            );
            $this->_helper->Redirect($url);
        }

        $table = new Cms_Model_DbTable_Xtension();
        $instances = $table->fetchAll("class='Flex' AND deleted=0 AND hidden=0");
        if($instances->count() == 1) {

            $instance = $instances->current();

            $table = new Cms_Model_DbTable_Container();
            $containerId = $table->addContainer(array(
                'page_id' => $pageId,
                'placeholder_id' => $placeholderId,
                'sort' => $sort,
                'language_id' => $languageId,
                'item_id' => $flexId,
                'controller' => 'Flex_IndexController',
                'instance_id' => $instance->id
            ));
            WSB_Log::info(sprintf('Added container with id %s', $containerId));

			Zend_Loader::loadFile('IndexController.php', WSB_XTENSION_PATH . 'flex/controllers/', true);

            $XT = new Flex_IndexController();
			$XT->setModule($instance);
            if ($XT instanceof WSB_Xtension_Base) {

                // Container holen und setzen
                $where = $table->getAdapter()->quoteInto('id=?', $containerId);
                $container = $table->fetchRow($where);
                $XT->setContainer($container);

                // xthtml/index/edit/id/2/
                $referer = Cms_Url::containerEditUrl($params['page_id']);
                $this->_helper->Redirect(Cms_Url::xtensionEditorUrl($containerId, $XT, $referer));
            }

            if($this->_getParam('TEMPLATE') == 'popup') {
                $this->_response->appendBody('
                <script type="text/javascript">
                    window.opener.location.reload();
                    window.close();
                </script>
                ');
            } else {
              $this->_helper->Redirect(Cms_Url::containerEditUrl($this->_getParam('page_id')));
            }

        }

    }

    public function selectControllerAction()
	{
        $instance_id = $this->_getParam('instance_id');
        if(!empty($instance_id) && is_numeric($instance_id)) {
        	$table = new Cms_Model_DbTable_Xtension();
        	$where = $table->getAdapter()->quoteInto('id=?', $instance_id);
            $instance = $table->fetchRow($where);

            $tmpControllers = $instance->getDescriptor()->getControllers();
            $controllers = array();
            foreach($tmpControllers AS $c) {
            	$desc = '';
            	if(!empty($c['label'])) {
            		$desc = sprintf('<b>%s</b>', $c['label']);
            	}
            	if(!empty($c['description'])) {
            		$desc .= sprintf(' %s', $c['description']);
            	}
            	if(empty($desc)) {
            		$desc = $c['class'];
            	}
				$controllers[] = array(
					'key' => $c['key'],
					'class' => $c['class'],
					'description' => $desc
				);
            }

            if(count($controllers) > 1) {

		    	$this->view->controllers = $controllers;

    			// Settings fuer htmlTable-Viewhelper
				$this->view->columns = array(
					array('key' => 'description', 'label' => $this->_helper->Translate('container:controller'), 'sortable' => 'true'),
					array('key' => 'icons', 'label' => '')
				);
				$this->view->fields = array(
					array('key' => 'description'),
					array('key' => 'icons', 'callback' => array('Cms_ContainerController', 'callbackSelectControllerLink'))
				);
				$this->view->settings = array('sortedBy' => array(
					'key' => 'description', 'dir' => 'asc')
				);

            } else if(count($controllers) == 1) {
            	$controller = reset($controllers);
				$url = Cms_Url::containerAddContainerUrl(
					$this->_getParam('page_id'),
					$this->_getParam('placeholder_id'),
					$this->_getParam('sort'),
					$this->_getParam('instance_id'),
					$this->_getParam('language_id'),
					$controller['class']
				);
				$this->_helper->Redirect($url);
            } else {
            	throw new Exception('Keine Controller definiert in descriptor.xml des Moduls ' . $instance->name);
            }

        }

        $this->render();

    	// Page Tree rendern
    	$this->render('container-tree', 'left', true);

    }

    public function selectModuleAction()
	{

        $this->view->isPopup = ($this->_getParam('TEMPLATE') == 'popup');

        // Flex-Inhalte holen
        require_once(WSB_XTENSION_PATH . 'flex/models/Table.php');
    	$table = new Flex_Model_Table();
    	$where = $table->getAdapter()->quoteInto('deleted=?', 0);
    	$test = $table->fetchAll($where, 'name ASC');
        $flexOptions = array('' => '') + $table->fetchPairs('id', 'name', $where, 'name ASC');
    	$this->view->flexOptions = $flexOptions;

    	$table = new Cms_Model_DbTable_Xtension();
    	$where = $table->getAdapter()->quoteInto('deleted=?', 0);
    	$this->view->modules = $table->fetchAll($where, 'name ASC');

    	// Settings fuer htmlTable-Viewhelper
		$this->view->columns = array(
			array('key' => 'id', 'label' => $this->_helper->Translate('module.id'), 'sortable' => 'true'),
			array('key' => 'name', 'label' => $this->_helper->Translate('module.name'), 'sortable' => 'true'),
			array('key' => 'class', 'label' => $this->_helper->Translate('module.class'), 'sortable' => 'true'),
			array('key' => 'icons', 'label' => '')
		);
		$this->view->fields = array(
			array('key' => 'id'),
			array('key' => 'name'),
			array('key' => 'class'),
			array('key' => 'icons', 'callback' => array('Cms_ContainerController', 'callbackSelectModuleLink'))
		);
		$this->view->settings = array('sortedBy' => array(
			'key' => 'name', 'dir' => 'desc')
		);

		$this->render();

    	// Page Tree rendern
    	$this->render('container-tree', 'left', true);
    }

    public static function callbackSelectControllerLink(array $controller)
	{
    	$request = Zend_Controller_Front::getInstance()->getRequest();
    	$pageId = $request->getParam('page_id');
    	$placeholderId = $request->getParam('placeholder_id');
    	$sort = $request->getParam('sort');
    	$languageId = $request->getParam('language_id');
    	$instanceId = $request->getParam('instance_id');
		$url = Cms_Url::containerAddContainerUrl($pageId, $placeholderId, $sort, $instanceId, $languageId, $controller['class']);
		return WSB_Controller_Url::getHtmlLink(WSB_Icon::add(), $url);
    }

    public static function callbackSelectModuleLink(Cms_Model_Xtension $module)
	{
    	$request = Zend_Controller_Front::getInstance()->getRequest();
    	$pageId = $request->getParam('page_id');
    	$placeholderId = $request->getParam('placeholder_id');
    	$sort = $request->getParam('sort');
    	$languageId = $request->getParam('language_id');
		$url = Cms_Url::containerSelectControllerUrl($pageId, $placeholderId, $sort, $module->id, $languageId);
		return WSB_Controller_Url::getHtmlLink(WSB_Icon::add(), $url);
    }

}
